package belf.migrate.api.sink.jdbc.helper;

import belf.migrate.api.sink.jdbc.KeyValue;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用于数据库一条记录更新前后的变动比较。<br/>
 * 假设变更前的before记录如下：
 * <pre>
 *    {"id":1,"name":"张三","age":25}
 * </pre>
 *  变更后的after记录如下：
 * <pre>
 *    {"id":1,"name":"张三","age":30,"city":"北京"}
 * </pre>
 * 则返回结果：
 * <pre>
 *    {"age":30,"city":"北京"}
 * </pre>
 */
public class BeforeAfterComparor {
    public static List<KeyValue> subtract(List<KeyValue> after, List<KeyValue> before) {
        if (null == before || before.isEmpty()) {
            return after;
        }

//        return CollectionUtils.subtract(after, before); //apache这个方法好，就是需要额外的包
        return after.stream()
                .filter(element -> !before.contains(element))
                .collect(Collectors.toList());
    }

    public static List<KeyValue> intersection(List<KeyValue> after, List<KeyValue> before) {
        if (after == null || before == null){
            return null;
        }

//        return (List<KeyValue>)CollectionUtils.intersection(after, before);

        List<KeyValue> sameElements = after.stream()
                .filter(before::contains)
                .collect(Collectors.toList());
        return sameElements;
    }
}
